<template>
  <div class="history-manage">
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="120px" inline>
        <el-form-item label="操作人账户名称">
          <el-input v-model="searchForm.plateformUserName" placeholder="请输入操作人账户名称" clearable />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="searchForm.operationType" placeholder="请选择操作类型" clearable>
            <el-option label="增加" value="0" />
            <el-option label="修改" value="1" />
            <el-option label="删除" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作状态">
          <el-select v-model="searchForm.operationStatus" placeholder="请选择操作状态" clearable>
            <el-option label="新增" value="0" />
            <el-option label="修改" value="1" />
            <el-option label="删除" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作结果">
          <el-select v-model="searchForm.operationResult" placeholder="请选择操作结果" clearable>
            <el-option label="成功" value="success" />
            <el-option label="失败" value="fail" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column prop="webPlatformUserId" label="操作人id" width="100" />
        <el-table-column prop="webName" label="操作人昵称" min-width="120">
          <template #default="scope">
            <div class="user-info">
              <el-avatar v-if="scope.row.webAvatar" :src="scope.row.webAvatar" size="small" />
              <span>{{ scope.row.webName || '-' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="webPhone" label="操作人手机号" width="150" />
        <el-table-column prop="webAction" label="操作行为" min-width="200" />
        <el-table-column prop="webActionType" label="操作类型" width="100">
        </el-table-column>
        <el-table-column prop="webActionResult" label="操作结果" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.webActionResult === 'success'" type="success">成功</el-tag>
            <el-tag v-else-if="scope.row.webActionResult === 'fail'" type="danger">失败</el-tag>
            <span v-else>{{ scope.row.webActionResult || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="webActionTime" label="操作时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.webActionTime) }}
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getWebHistoryInfo, WebHistoryParam } from '@/api/history/historyApi'

// 搜索表单
const searchForm = reactive({
  plateformUserId: undefined,
  plateformUserName: '',
  operationType: '',
  operationStatus: '',
  operationResult: '',
  operationTimeStart: '',
  operationTimeEnd: ''
})

// 日期范围
const dateRange = ref<string[]>([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref<any[]>([])

// 加载状态
const loading = ref(false)

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 构建请求参数
const buildParams = () => {
  const params = {
    ...searchForm,
    page: pagination.currentPage,
    pageSize: pagination.pageSize
  }

  // 处理日期范围
  if (dateRange.value && dateRange.value.length === 2) {
    params.operationTimeStart = dateRange.value[0]
    params.operationTimeEnd = dateRange.value[1]
  }

  return params
}

// 获取历史记录列表
const fetchHistoryList = async () => {
  loading.value = true
  try {
    const params = buildParams()
    const response = await getWebHistoryInfo(params)

    // 适配后端返回的数据格式
    if (response && response.data && response.code === '200') {
      tableData.value = response.data.list || []
      pagination.total = response.data.total || 0
    }
  } catch (error) {
    ElMessage.error('获取操作历史记录失败')
    console.error('获取操作历史记录失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchHistoryList()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key as keyof typeof searchForm] = ''
  })
  dateRange.value = []
  pagination.currentPage = 1
  fetchHistoryList()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchHistoryList()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.currentPage = current
  fetchHistoryList()
}

// 初始加载
onMounted(() => {
  fetchHistoryList()
})
</script>

<style scoped lang="scss">
.history-manage {
  padding: 20px;

  .page-header {
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 8px;

    .el-avatar {
      border-radius: 50%;
    }
  }
}
</style>
